package com.mp.tanlong;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.common.HybridBinarizer;
import com.mining.app.zxing.camera.CameraManager;
import com.mining.app.zxing.decoding.CaptureActivityHandler;
import com.mining.app.zxing.decoding.InactivityTimer;
import com.mining.app.zxing.view.ViewfinderView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

/**
 * Initial the camera
 * @author Ryan.Tang
 */
public class CaptureActivity extends Activity implements Callback {


	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;
	

    public static final int RESULT_CANCELED = 0;
    public static final int RESULT_OK = -1;
    public static final int RESULT_FIRST_USER = 1;
	public static final int RC_CHOOSE_PHOTO = 2;
	public static final int CAMERA_OK = -1;
	private Bitmap scanBitmap;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_capture);
		//ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);

		startQrCode();
		CameraManager.init(getApplication());
		viewfinderView = findViewById(R.id.viewfinder_view);
		
		Button mButtonBack = findViewById(R.id.button_back);
		mButtonBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				CaptureActivity.this.finish();
				
			}
		});

		Button button_rigth = findViewById(R.id.button_rigth);
		button_rigth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startQrCode();
				Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
				startActivityForResult(intent, RC_CHOOSE_PHOTO);

			}
		});

		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}
	// 开始扫码
	private void startQrCode() {
		// 申请相机权限
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
			ActivityCompat.requestPermissions(CaptureActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
			return;
		}
		// 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）READ_EXTERNAL_STORAGE
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
			// 申请权限
			ActivityCompat.requestPermissions(CaptureActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
			return;
		}

	}
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		switch (requestCode) {
			case 1:
				// 摄像头权限申请

				break;
			case 2:
				// 文件读写权限申请
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					// 获得授权
					startQrCode();
				} else {
					// 被禁止授权
					Toast.makeText(CaptureActivity.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
				}
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 		playBeepSoundAndVibrate();
	   Context mContext;
		if(resultCode==RESULT_OK&&data != null&&requestCode == RC_CHOOSE_PHOTO){
			Uri selectedImage = data.getData();
			final String pathResult =UrlUtil.getRealPathFromUri(getApplicationContext(),selectedImage);
			//final String pathResult="/storage/emulated/0/Pictures/WeiXin/mmexport1605108353402.png";
			//Log.e("hxy","pathResult:"+pathResult);
							String resultString =syncDecodeQRCode(getDecodeAbleBitmap(pathResult));
							Intent resultIntent =new Intent();
							resultIntent.putExtra("result", resultString);
							CaptureActivity.this.setResult(RESULT_OK,resultIntent);
						 	//Toast.makeText(CaptureActivity.this, "识别结果123:"+resultString,Toast.LENGTH_LONG).show();

//			new Thread(new Runnable() {
//				@SuppressLint("LongLogTag")
//				@Override
//				public void run() {
//					String resultString =syncDecodeQRCode(getDecodeAbleBitmap(pathResult));
//					//	Log.e("**********************************************************","str:"+resultString);
//					//Result result=scanningImage(pathResult);
//					if(resultString==null){
//						Looper.prepare();
//						Toast.makeText(CaptureActivity.this, "未识别到二维码!",Toast.LENGTH_LONG).show();
//						Looper.loop();
//					}else{
//
//							Intent resultIntent =new Intent();
//							resultIntent.putExtra("result", resultString);
//							CaptureActivity.this.setResult(RESULT_OK,resultIntent);
//							CaptureActivity.this.finish();
//						 Looper.prepare();
//						 	Toast.makeText(CaptureActivity.this, "识别结果123:"+resultString,Toast.LENGTH_LONG).show();
//						 Looper.loop();
//
//					}
//
//				}
//			}).start();
			CaptureActivity.this.finish();
		}

	}

	 /**
     * 同步解析bitmap二维码。该方法是耗时操作，请在子线程中调用。
     *
     * @param bitmap 要解析的二维码图片
     * @return 返回二维码图片里的内容 或 null
     */
    @SuppressLint("LongLogTag")
	public static String syncDecodeQRCode(Bitmap bitmap) {
        Result result;
        RGBLuminanceSource source = null;
		final Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
			List<BarcodeFormat> allFormatList = new ArrayList<>();
			allFormatList.add(BarcodeFormat.AZTEC);
			allFormatList.add(BarcodeFormat.CODABAR);
			allFormatList.add(BarcodeFormat.CODE_39);
			allFormatList.add(BarcodeFormat.CODE_93);
			allFormatList.add(BarcodeFormat.CODE_128);
			allFormatList.add(BarcodeFormat.DATA_MATRIX);
			allFormatList.add(BarcodeFormat.EAN_8);
			allFormatList.add(BarcodeFormat.EAN_13);
			allFormatList.add(BarcodeFormat.ITF);
			allFormatList.add(BarcodeFormat.MAXICODE);
			allFormatList.add(BarcodeFormat.PDF_417);
			allFormatList.add(BarcodeFormat.QR_CODE);
			allFormatList.add(BarcodeFormat.RSS_14);
			allFormatList.add(BarcodeFormat.RSS_EXPANDED);
			allFormatList.add(BarcodeFormat.UPC_A);
			allFormatList.add(BarcodeFormat.UPC_E);
			allFormatList.add(BarcodeFormat.UPC_EAN_EXTENSION);
			// 可能的编码格式
			hints.put(DecodeHintType.POSSIBLE_FORMATS, allFormatList);
			// 花更多的时间用于寻找图上的编码，优化准确性，但不优化速度
			hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
			// 复杂模式，开启 PURE_BARCODE 模式（带图片 LOGO 的解码方案）
            //hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
			// 编码字符集
			hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
        try {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int[] pixels = new int[width * height];
            bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
            source = new RGBLuminanceSource(width, height, pixels);
            result = new MultiFormatReader().decode(new BinaryBitmap(new HybridBinarizer(source)), hints);
            	//	Log.e("**********************************************************","str:"+result.getText());
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
            if (source != null) {
                try {
                    result = new MultiFormatReader().decode(new BinaryBitmap(new GlobalHistogramBinarizer(source)), hints);
            	//	Log.e("**********************************************************","str:"+result.getText());
                    return result.getText();
                } catch (Throwable e2) {
                    e2.printStackTrace();
                }
            }
            return null;
        }
    }
 public static Bitmap getDecodeAbleBitmap(String picturePath) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(picturePath, options);
            int sampleSize = options.outHeight / 400;
            if (sampleSize <= 0) {
                sampleSize = 1;
            }
            options.inSampleSize = sampleSize;
            options.inJustDecodeBounds = false;

            return BitmapFactory.decodeFile(picturePath, options);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}
	
	/**
	 * 处理扫描结果
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		String resultString = result.getText();
		if (resultString.equals("")) {
			Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
		}else {
			Intent resultIntent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString("result", resultString);
			//bundle.putParcelable("bitmap", barcode);

	       ByteArrayOutputStream baos=new ByteArrayOutputStream();
	       barcode.compress(Bitmap.CompressFormat.PNG, 100, baos);
	       byte [] bitmapByte =baos.toByteArray();
	       bundle.putByteArray("bitmap",bitmapByte);

//		       if (scan_type.equals(CaptureActivity.SCAN_TYPE_QRCODESCAN)) {
//               rawResult = multiFormatReader.decodeWithState(bitmap);//解析二维码图片
//
//               }
	       
//	       if (scan_type.equals(CaptureActivity.SCAN_TYPE_QRCODESCAN)) {
//               rawResult = multiFormatReader.decodeWithState(bitmap);//解析二维码图片
//           } else if (scan_type.equals(CaptureActivity.SCAN_TYPE_BANK_CARD)) {
//               result = BankCardIdentify.bankCardIdentify(activity, toBitmap(source, source.renderCroppedGreyscaleBitmap()));//解析银行卡
//           } else {
//               result = IdCardIdentify.idCardIdentify(activity, toBitmap(source, source.renderCroppedGreyscaleBitmap()));  //解析身份证
//           }
	       
	       
			resultIntent.putExtras(bundle);
			this.setResult(RESULT_OK, resultIntent);
		}
		CaptureActivity.this.finish();
	}
	
	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};



}

